package com.docker.manege.container;

import com.alibaba.fastjson.JSONObject;
import com.docker.comment.ShellUtil;
import com.docker.core.mvc.Remark;
import com.docker.core.third.docker.DockerKit;
import com.docker.core.third.websocket.BaseWebsocketController;
import com.docker.core.third.websocket.WebsocketPool;
import com.jfinal.aop.Aop;
import com.jfinal.kit.StrKit;

import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @Author: zhl
 * @Create: 2021/1/20 10:38
 **/
@Remark("命令行执行")
@ServerEndpoint("/websocket/container/cmd")
public class ContainerCMDWebsocket extends BaseWebsocketController {

    private ContainerService service = Aop.get(ContainerService.class);

    @Override
    protected void onOpenBefore(Session session, String connectKey) {
    }

    @Override
    public void onOpenAfter(Session session, String connectKey) {
//        容器id
        String containerId = session.getRequestParameterMap().get("container_id").get(0);
        if (StrKit.isBlank(containerId)) {
            throwError("容器参数不能为空");
        }
//        连接token
        String token = session.getRequestParameterMap().get("token").get(0);
//        服务id
        String serverId = session.getRequestParameterMap().get("server_id").get(0);
//        docker客户端连接key
        String clientKey = DockerKit.key(token, serverId);

        ShellUtil.putOutputStream(connectKey);
        try {
            DockerKit.execInstance(clientKey, connectKey, containerId, "/bin/bash");
        }catch (Exception e){
//            防止内存泄漏
            ShellUtil.close(connectKey);
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(WebsocketPool socketPool, JSONObject msgJson) {
        try {
            ShellUtil.transToDocker( socketPool.getConnect_key(), msgJson.getJSONObject("data").getString("data"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCloseBefore(Session session, String connectKey) {
        ShellUtil.close(connectKey);
    }

    @Override
    protected void onCloseAfter(Session session, String connectKey) {
    }

    @Override
    protected void onErrorBefore(Session session, String connectKey) {
    }

    @Override
    protected void onErrorAfter(Session session, String connectKey) {
    }

}
